package com.jingdianjichi.subject.infra.basic.service.impl;

import com.alibaba.fastjson.JSON;
import com.jingdianjichi.subject.infra.basic.entity.SubjectInfoTestES;
import com.jingdianjichi.subject.infra.basic.esRepo.SubjectESRepository;
import com.jingdianjichi.subject.infra.basic.service.SubjectEsTestService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Description
 *
 * @author: WuYimin
 * Date: 2024-02-18
 */
@Service
@Slf4j
public class SubjectEsTestServiceImpl implements SubjectEsTestService {

	@Resource
	private ElasticsearchRestTemplate elasticsearchRestTemplate;

	@Resource
	private SubjectESRepository subjectESRepository;

	@Override
	public void createIndex() {
		IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(SubjectInfoTestES.class);
		indexOperations.create();
		Document mapping = indexOperations.createMapping(SubjectInfoTestES.class);
		indexOperations.putMapping(mapping);
	}

	@Override
	public void addDocs() {
		List<SubjectInfoTestES> list = new ArrayList<>();
		list.add(new SubjectInfoTestES(1L,"redis是什么","redis是一个缓存","书生",new Date()));
		list.add(new SubjectInfoTestES(2L,"MySQL是什么","MySQL是一个数据库","书生",new Date()));
		subjectESRepository.saveAll(list);
	}


	@Override
	public void find() {
		Iterable<SubjectInfoTestES> all = subjectESRepository.findAll();
		for (SubjectInfoTestES subjectInfoTestES : all) {
			log.info("subjectInfoES：{}",JSON.toJSONString(subjectInfoTestES));
		}
	}

	@Override
	public void search() {
		NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
				.withQuery(QueryBuilders.matchQuery("subjectName","redis"))
				.build();
		SearchHits<SubjectInfoTestES> search = elasticsearchRestTemplate.search(nativeSearchQuery, SubjectInfoTestES.class);
		List<SearchHit<SubjectInfoTestES>> searchHits = search.getSearchHits();
		log.info("searchHit：{}", JSON.toJSONString(searchHits));
	}
}
